<html>
<head>
    <meta charset="utf-8"/>
    <title>Zadatak 1</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="js/jquery-1.11.0.min.js"></script>
    <script>
        var studenti;

        function sortByKey(array, key) {
            return array.sort(function(a, b) {
                var x = a[key]; var y = b[key];
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            });
        }

        function ispisiStudente(){
            //animacija
            $("#readStudentRes").fadeOut("fast", function(){

                //cistimo ul
                $("#readStudentRes").empty();

                studenti.forEach(function(entry){
                        var li = '<li><a href="studentProfil.php?indeks=';
                        li += entry.indeks;
                        li += '">';
                        li += entry.ime + " " + entry.prezime + " " + entry.indeks;
                        li += '</a></li>';
                        //alert(li);
                        $("#readStudentRes").append(li);
                    }
                );
                //animacija

                $("#readStudentRes").fadeIn();
            });
        }

        function sortiraj(){
            studenti = sortByKey(studenti,$("#sortOpt").val());
            ispisiStudente();
        }

        function readStudents(){
            //alert($('#qStudent').val());
            var request;
            request = $.ajax(
                {
                    url: "ajaxReadStudent.php",
                    type: "get",
                    data: "q=" + $("#qStudent").val()
                }
            );

            request.done( function (response, textStatus, jqXHR) {
                    studenti = JSON.parse(response);

                    ispisiStudente();
                }
            );

            request.fail(function (jqXHR, textStatus, errorThrown){
                // log the error to the console
                alert("The following error occured: "+errorThrown);
            });
        }

    </script>


</head>

<body onload="readStudents()">

<div id="content">
    <h2>Izaberi studenata</h2>
    <label>Pretraga studenata: </label>
    <input type="text" id="qStudent" name="qStudent" onkeyup="readStudents()">
    <br>
    <label>Sortiranje:</label>
    <select id="sortOpt">
        <option value="ime">Ime</option>
        <option value="prezime">Prezime</option>
        <option value="indeks">Indeks</option>
    </select>
    <button onclick="sortiraj()">Sortiraj</button>
    <br>
    <ul id="readStudentRes">
    </ul>
</div>


</body>
</html>

